package com.freshcity.upload
{
	import com.adobe.images.JPGEncoder;
	import com.adobe.images.PNGEncoder;
	import com.adobe.protocols.dict.events.DatabaseEvent;
	import com.adobe.serialization.json.JSON;
	import com.demonsters.debugger.MonsterDebugger;
	import com.freshcity.lib.event.DataEvent;
	import com.freshcity.lib.event.EventName;
	import com.freshcity.upload.event.UploadEvent;
	
	import fl.controls.Button;
	
	import flash.display.BitmapData;
	import flash.display.MovieClip;
	import flash.display.SimpleButton;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.MouseEvent;
	import flash.events.TimerEvent;
	import flash.external.ExternalInterface;
	import flash.geom.Matrix;
	import flash.geom.Rectangle;
	import flash.net.URLRequest;
	import flash.net.URLRequestHeader;
	import flash.net.URLRequestMethod;
	import flash.text.TextField;
	import flash.utils.*;

	[SWF(width="800", height="500", frameRate="30")]
	public class CutView extends Sprite
	{
		public function CutView()
		{
			super();
			this.avatarModel = new AvatarModel();
			MonsterDebugger.initialize(this);
			
			if (stage)
			{
				this.init();
			}
			else
			{
				addEventListener(Event.ADDED_TO_STAGE, this.init);
			}
			return;
		}

		public function showCameraArea(arg1:MouseEvent):void
		{
			this.cameraBtnRemoveEvents();
			this.browseComp.btnBrowsAddEvents();
			if (this.cameraArea != null)
			{
				if (this.cameraArea.visible == false)
				{
					this.cameraArea.visible=true;
				}
			}
			else
			{
				this.cameraArea=new CameraComp(this);
				this.cameraArea.x=199;
				this.cameraArea.y=80;
				addChild(this.cameraArea);
			}
			this.browseComp.label.visible=false;
			this.localPicArea.visible=false;
			this.avatarArea.visible=false;
			this.splitLines.visible=false;
			if (!(this.saveBtn == null) && this.saveBtn.visible == true)
			{
				var loc1:*;
				this.cancleBtn.visible=loc1=false;
				this.saveBtn.visible=loc1;
			}
			return;
		}

		public function addSaveBtns():void
		{
			if (this.saveBtn == null)
			{
				this.saveBtn=new Button();
				this.saveBtn.label="保存";
				this.saveBtn.width=60;
				this.saveBtn.height=25;
				this.saveBtn.x=20;
				this.saveBtn.y=450;
				this.cancleBtn=new Button();
				this.cancleBtn.label="取消";
				this.cancleBtn.width=60;
				this.cancleBtn.height=25;
				this.cancleBtn.x=100;
				this.cancleBtn.y=450;
				addChild(this.saveBtn);
				addChild(this.cancleBtn);
				
				var loc1:*=new flash.text.TextFormat("宋体", 12, 0xff0000);
				this.validMsg = new TextField();
				this.validMsg.width = 200;
				this.validMsg.x = 200;
				this.validMsg.y = 450;
				this.validMsg.setTextFormat(loc1);	
				addChild(this.validMsg);
			}
			this.saveBtn.mouseEnabled=true;
			this.saveBtn.addEventListener(MouseEvent.CLICK, this.updateAvatar);
			this.cancleBtn.addEventListener(MouseEvent.CLICK, this.cancelProgramm);
			return;
		}

		public function updateAvatar(arg1:MouseEvent):void
		{
			var loc3:*=this.avatarArea.bigPic;
			loc3.smoothing=true;
			var loc4:*=loc3.bitmapData;
			var w:Number=loc4.width;
			var h:Number=loc4.height;
			var bitmapData:BitmapData=new BitmapData(w, h);
			bitmapData.draw(loc4, new Matrix(loc3.scaleX, 0, 0, loc3.scaleX, 0, 0), null, null, new Rectangle(0, 0, w, h));
			//var loc8:*=new JPGEncoder(100);
			//var loc9:*=loc8.encode(loc7);
			var encoder:JPGEncoder = new JPGEncoder(100);
			var bytes:ByteArray = encoder.encode(bitmapData);
			//var bytes:ByteArray = PNGEncoder.encode(bitmapData);
			if(bytes.length< 2*1024*1024){
				this.saveBtn.mouseEnabled=false;
				this.saveBtn.alpha=0.5;
				stage.dispatchEvent(new DataEvent(EventName.SavePic,{content:bytes}));
			}else{
				validMsg.text = "文件大小超过2M，请重新上传。";
			}
			
			/*
			if (Param.limited == null || Param.limited == "1")
			{
				if (ExternalInterface.available)
				{
					ExternalInterface.call(Param.jsFunc, "M01106");
				}
				return;
			}
			if (!(Param.verifyCode == null) && Param.verifyCode == "4")
			{
				if (ExternalInterface.available)
				{
					ExternalInterface.addCallback("beginUploadAvatar", this.beginUploadAvatar);
					ExternalInterface.call("App.verifyCode", {"cb": "beginUploadAvatar", "type": "flash"});
				}
			}
			else
			{
				this.beginUploadAvatar();
			}
			*/
		}

		private function beginUploadAvatar():void
		{
			addChild(this._loadingPanel);
			var loc1:*=new Timer(300);
			loc1.addEventListener(TimerEvent.TIMER, this.onTimerEvt);
			loc1.start();
			return;
		}

		private function onTimerEvt(arg1:TimerEvent):void
		{
			var loc1:*=arg1.target as Timer;
			loc1.removeEventListener(TimerEvent.TIMER, this.onTimerEvt);
			loc1.stop();
			if (this.avatarModel.type != 2)
			{
				this.uploadAvatar();
			}
			else
			{
				this.uploadAvatar();
			}
			return;
		}

		private function uploadSourcePic():void
		{
			var loc1:*=Param.ticket[0][0];
			var loc2:*=Param.sourcePicURL + "?s=json&app=miniblog&data=1&mime=image/jpeg&ticket=" + loc1 + "&ct=" + new Date().getTime();
			Param.ticket.shift();
			Param.getTicket();
			var loc3:*=this.avatarModel.imgData;
			var loc4:*=new URLRequestHeader("Content-type", "application/octet-stream");
			var loc5:*;
			(loc5=new URLRequest(loc2)).requestHeaders.push(loc4);
			loc5.method=URLRequestMethod.POST;
			loc5.data=loc3;
			var loc6:*;
			(loc6=new flash.net.URLLoader()).addEventListener(Event.COMPLETE, this.uploadSourceComplete);
			loc6.addEventListener(IOErrorEvent.IO_ERROR, this.sourceErrorHandler);
			loc6.load(loc5);
			return;
		}

		private function sourceErrorHandler(arg1:IOErrorEvent):void
		{
			var loc1:*=arg1.target as flash.net.URLLoader;
			loc1.removeEventListener(Event.COMPLETE, this.uploadSourceComplete);
			loc1.removeEventListener(IOErrorEvent.IO_ERROR, this.sourceErrorHandler);
			if (ExternalInterface.available)
			{
				ExternalInterface.call(Param.jsFunc, "M00004");
			}
			return;
		}

		private function uploadSourceComplete(arg1:Event):void
		{
			var loc1:*=arg1.target as flash.net.URLLoader;
			loc1.removeEventListener(Event.COMPLETE, this.uploadSourceComplete);
			loc1.removeEventListener(IOErrorEvent.IO_ERROR, this.sourceErrorHandler);
			var loc2:*=loc1.data.match(new RegExp("\\{.+\\}"))[0];
			var loc3:*;
			if ((loc3=JSON.decode(loc2))["code"] != "A00006")
			{
				if (ExternalInterface.available)
				{
					ExternalInterface.call(Param.jsFunc, "M00004");
				}
			}
			else
			{
				this._sourcePID=loc3["data"]["pics"]["pic_1"]["pid"];
				this.uploadAvatar();
			}
			return;
		}

		private function uploadAvatar():void
		{
			var loc1:*=Param.ticket[0][0];
			var loc2:*=Param.imgUrl + "?oldver=" + Param.ver + "&product=miniblog&ticket=" + loc1 + "&ct=" + new Date().getTime();
			Param.ticket.shift();
			Param.getTicket();
			var loc3:*=this.avatarArea.bigPic;
			loc3.smoothing=true;
			var loc4:*;
			var loc5:*=(loc4=loc3.bitmapData).width;
			var loc6:*=loc4.height;
			var loc7:*;
			(loc7=new BitmapData(180, 180)).draw(loc4, new Matrix(loc3.scaleX, 0, 0, loc3.scaleX, 0, 0), null, null, new Rectangle(0, 0, 180, 180));
			var loc8:*;
			var loc9:*=(loc8=new JPGEncoder(100)).encode(loc7);
			var loc10:*=new URLRequestHeader("Content-type", "application/octet-stream");
			var loc11:*;
			(loc11=new URLRequest(loc2)).requestHeaders.push(loc10);
			loc11.method=URLRequestMethod.POST;
			loc11.data=loc9;
			var loc12:*;
			(loc12=new flash.net.URLLoader()).addEventListener(Event.COMPLETE, this.uploadComplete);
			loc12.addEventListener(IOErrorEvent.IO_ERROR, this.errorHandler);
			loc12.load(loc11);
			return;
		}

		private function uploadComplete(arg1:Event):void
		{
			var evt:Event;
			var loader:flash.net.URLLoader;
			var _json:String;
			var returnData:Object;
			var delAndVersion:flash.net.URLLoader;
			var _delurl:String;
			var _suc:Boolean;
			var _ticket:String;

			var loc1:*;
			_delurl=null;
			_suc=false;
			_ticket=null;
			evt=arg1;
			if (contains(this._loadingPanel))
			{
				removeChild(this._loadingPanel);
			}
			loader=evt.target as flash.net.URLLoader;
			loader.removeEventListener(Event.COMPLETE, this.uploadComplete);
			loader.removeEventListener(IOErrorEvent.IO_ERROR, this.errorHandler);
			_json=loader.data.match(new RegExp("\\{.+\\}"))[0];
			returnData=JSON.decode(_json);
			delAndVersion=new flash.net.URLLoader();
			if (returnData["ret"] != "1")
			{
				_suc=false;
			}
			else
			{
				_suc=true;
			}
			if (_suc)
			{
				_ticket=Param.ticket[0][0];
				Param.ticket.shift();
				Param.getTicket();
				_delurl=Param.delUrl + "?ver=" + returnData["ver"] + "&status=1&ticket=" + _ticket + "&type=" + this.avatarModel.type + "&pid=" + this._sourcePID + "&ct=" + new Date().getTime();
				delAndVersion.load(new URLRequest(_delurl));
				delAndVersion.addEventListener(Event.COMPLETE, this.delComplete);
			}
			else
			{
				try
				{
					ExternalInterface.call(Param.jsFunc, "M00004");
				}
				catch (e:Error)
				{
				}
				;
			}
			return;
		}

		private function delComplete(arg1:Event):void
		{
			var evt:Event;
			var delAndVersion:flash.net.URLLoader;
			var requestJson:Object;

			var loc1:*;
			evt=arg1;
			delAndVersion=evt.target as flash.net.URLLoader;
			delAndVersion.removeEventListener(Event.COMPLETE, this.delComplete);
			requestJson=JSON.decode(delAndVersion.data);
			if (requestJson["code"] != "A00006")
			{
				try
				{
					ExternalInterface.call(Param.jsFunc, "M00004");
				}
				catch (e:Error)
				{
				}
				;
			}
			else
			{
				try
				{
					ExternalInterface.call(Param.jsFunc, "A00006");
				}
				catch (e:Error)
				{
				}
				;
			}
			return;
		}

		private function errorHandler(arg1:IOErrorEvent):void
		{
			var loc1:*=arg1.target as flash.net.URLLoader;
			loc1.removeEventListener(IOErrorEvent.IO_ERROR, this.errorHandler);
			return;
		}

		private function cancelProgramm(arg1:MouseEvent):void
		{
			stage.dispatchEvent(new DataEvent(EventName.CancelPicEdit,{}));
		}

		private function init(arg1:Event=null):void
		{
			removeEventListener(Event.ADDED_TO_STAGE, this.init);
			var background:SK_Background = new SK_Background();
			background.closeBtn.addEventListener(MouseEvent.CLICK,cancelProgramm);
			addChild(background);				
			
			this.splitLines = new flash.display.Shape();
			this.splitLines.graphics.lineStyle(1, 15066597);
			this.splitLines.graphics.lineTo(0, 310);
			this.splitLines.x = 349.5;
			this.splitLines.y = 90;
			this.browseComp = new BrowseComp(this.avatarModel);
			this.browseComp.x = 20;
			this.browseComp.y = 5;
			
			this.cameraBtn = new SK_BtnCamera();
			this.cameraBtn.x = 155;
			this.cameraBtn.y = 5;
			this.cameraBtnAddEvents();
			this.avatarArea = new AvatarArea();
			this.avatarArea.y = 94;
			this.avatarArea.x = 360;
			this.localPicArea = new LocalPicArea();
			this.localPicArea.x = 20;
			this.localPicArea.y = 100;
			addChild(this.localPicArea);
			this.avatarModel.addEventListener(UploadEvent.IMAGE_CHANGE, this.changeAvatars);
			this.avatarModel.addEventListener(UploadEvent.IMAGE_INIT, this.initAvatars);
			var loc2:*=700;
			var loc3:*=500;
			this._loadingPanel = new Sprite();
			this._loadingPanel.graphics.beginFill(0, 0.4);
			this._loadingPanel.graphics.drawRect(0, 0, loc2, loc3);
			this._loadingPanel.graphics.endFill();
			var loc4:*;
			(loc4 = new SK_Loading() as MovieClip).mouseEnabled = false;
			loc4.x = (loc2 - loc4.width) * 0.5;
			loc4.y = (loc3 - loc4.height) * 0.5;
			this._loadingPanel.addChild(loc4);
			this._loadingPanel.mouseChildren = false;
			
			
			addChild(this.splitLines);
			addChild(this.browseComp);
			addChild(this.avatarArea);
			addChild(this.cameraBtn);
		}

		public function cameraBtnAddEvents():void
		{
			this.cameraBtn.addEventListener(MouseEvent.CLICK, this.showCameraArea);
		}

		private function cameraBtnRemoveEvents():void
		{
			this.cameraBtn.removeEventListener(MouseEvent.CLICK, this.showCameraArea);
		}

		private function changeAvatars(arg1:UploadEvent):void
		{
			this.addSaveBtns();
			this.localPicArea.loaddingUI.visible=false;
			if (!(this.cameraArea == null) && this.cameraArea.visible == true)
			{
				this.cameraArea.visible=false;
				this.cameraBtnAddEvents();
			}
			this.localPicArea.visible=true;
			this.localPicArea.setLocalPicSize(this.avatarModel.bmd);
			return;
		}

		private function initAvatars(arg1:UploadEvent):void
		{
			this.avatarArea.initAvatars(this.avatarModel.bmd);
			return;
		}

		private var _loadingPanel:flash.display.Sprite;

		private var _avatarAreaMove:Boolean=true;

		private var _sourcePID:String="";

		public var avatarModel:AvatarModel;

		public var splitLines:flash.display.Shape;

		public var avatarArea:AvatarArea;

		public var localPicArea:LocalPicArea;

		public var cameraArea:CameraComp;

		public var browseComp:BrowseComp;

		public var cameraBtn:SimpleButton;

		public var saveBtn:Button;

		public var cancleBtn:Button;
		private var validMsg:TextField;

	}
}
